<?php

namespace app\merchants\middleware;


use app\common\traits\AuthTrait;
use app\merchants\loader\Services;
use think\Exception;
use think\facade\Config;

/**
 * 认证类
 */
class Auth
{
    use AuthTrait;

    /**
     * @param          $request
     * @param \Closure $next
     * @return mixed|void
     * @throws \Exception
     */
    public function handle($request, \Closure $next)
    {
        try {
            $header = $request->header();
            // 提取header的APP
            $request->request_app = $this->parseHeaderApp($header);

            $no_auth = Config::get('config');

            if ($this->checkNoAuth($request, $no_auth['no_auth'] ?? [])) {
                return $next($request);
            }
            // 获取header的认证信息
            $authorization = $this->parseHeaderAuthorization($header);
            if (empty($authorization)) {
                api_result(API_TIMEOUT, '登录超时,请重新登录');
            }

            // 验证用户信息
            $errorMsg = '';

            $adminInfo = Services::Merchant()->verityLogin($authorization, $request->request_app, $errorMsg);
            if ($adminInfo === false) {
                api_result(API_ERROR, $errorMsg);
            }

            // 验证权限是否需要验证
//            if (!Services::Merchant()->checkAuthPermission($request->action(), $adminInfo['group_id'])) {
//                api_result(API_ACCESS_DENIED, "您没有该操作权限");
//            }
            // 用户信息 保存到post中
            $request->adminUser = $adminInfo;
            return $next($request);
        } catch (Exception $e) {
            api_result($e);
        }
    }

    public function parseHeaderAuthorization(array $header)
    {
        $authStr = $header[$this->_authField] ?? '';
        if (empty($authStr)) {
            $authStr = $header[ucfirst($this->_authField)] ?? '';
        }
        return strpos($authStr, ' ') !== false ? explode(' ', $authStr)[1] : $authStr;
    }
}
